<template>
  <commonformdialog :dialogWidth="'60%'" :isshowDialogs="isshowDialog" :dialogTitle="dialogTitle" @closetextDialog="closeDialog"
    @confirmbtn="confirmbtn">
    <!-- form表单区域 -->
    <div class="formarea">
      <el-form ref="xlcform" size="medium" :rules="rules" :model="xlcforms" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="上级机构" prop='parent_id'>
              <treeselect v-model="xlcforms.parent_id" :options="treeOptions" :default-expand-level="1" :normalizer="normalizer"
                placeholder="请选择上级机构" @select="changeparent_id" v-if="xlcforms.parent_idTitle=='' || formTypejg==0" />
              <el-input v-else v-model="xlcforms.parent_idTitle" clearable disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择城市" prop="city">
              <el-cascader size="large" clearable placeholder="请选择城市" :disabled="xlcforms.type==1" :options="options"
                v-model="xlcforms.city" :show-all-levels="true" @change='changeArea' style="width: 100%"></el-cascader>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="机构名称" prop='title'>
              <el-input v-model="xlcforms.title" placeholder="请输入机构名称"  clearable></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="机构类型" prop='type'>
              <el-select v-model="xlcforms.type" clearable placeholder="请选择机构类型" style="width: 100%;" :disabled="xlcforms.parent_id==null || xlcforms.type==1">
                <el-option v-for="item in typeOption" :key="item.val+'-only'" :label="item.title" :value="item.val"
                  :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'联\u2000系\u2000人'" prop='nickname'>
              <el-input v-model="xlcforms.nickname" :disabled="formTypejg==1" clearable placeholder="请输入联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop='tel'>
              <el-input v-model="xlcforms.tel" :disabled="formTypejg==1" clearable placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="运营方式" prop="is_partner">
              <el-radio-group v-model="xlcforms.is_partner" :disabled="xlcforms.type==1">
                <el-radio :label="0">直营</el-radio>
                <el-radio :label="1">加盟</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务网点" prop="is_branch">
              <el-radio-group v-model="xlcforms.is_branch">
                <el-radio :label="1" :disabled="xlcforms.type==4">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">
            <el-form-item label="基础设施" prop="facilities">
              <el-checkbox-group v-model="xlcforms.facilities" size="medium">
                <el-checkbox v-for="(item, index) in facilitiesOption" :key="index+'-only'" :label="item.id" :disabled="item.disabled">
                  {{ item.title }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">
            <el-form-item :label="'封\u2000面\u2000图'" prop="head_img">
              <uploader :initUrl="xlcforms.head_img" @uploadimgok="head_imgok"
                @deleteimg='head_imgdel'>
                <span slot="text">
                  支持上传不大于10M的JPEG、JPG、PNG、BMP图片
                </span>
              </uploader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item :label="'详\u2000情\u2000图'" prop="picture">
              <uploader :initUrl="xlcforms.picture" @uploadimgok="pictureok"
                @deleteimg='picturedel' :fixedNumber="[2,1]">
                <span slot="text">
                  支持上传不大于10M的JPEG、JPG、PNG、BMP图片
                </span>
              </uploader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="机构地址" prop="address">
              <el-input placeholder="请点击右边选择地图来选择地址" :disabled="true" v-model="xlcforms.address">
                <template slot="append">
                  <el-button @click="selectmap">选择地图</el-button>
                </template>
              </el-input>
            </el-form-item>
            <mapDialog v-if="isshowmap" :isshowmapDialog="isshowmap" @closemap="closemap" @affirmMaps="affirmMap"
              :userSelectinfo="selectmapinfo"></mapDialog>
          </el-col>
        </el-row>

      </el-form>

    </div>

  </commonformdialog>
</template>

<script>
  //弹窗外壳
  import commonformdialog from '@/components/commondialog/commondialog'
  //地图弹窗组件
  import mapDialog from '@/components/selectmap/selectmap'
  //引入图片上传组件
  import uploader from '@/components/uploadImgNew/uploadImgNew'
  import Treeselect from "@riophae/vue-treeselect"; //下拉树组件

  import {
    schoolteam,
    schoolteamread,
    schoolteamcreate
  } from '@/api/school'
  //获取sessionStorage
  //api
  import {
    getArea,

  } from '@/api/common'
  import {
    getSessionStorage
  } from '@/utils/accessToken'
  export default {
    data() {
      return {
        //用户选择的地图
        selectmapinfo: {},
        //是否显示地图
        isshowmap: false,

        treeOptions: [],
        facilitiesOption: [],
        //训练场表单
        xlcforms: {
          parent_id: null,
          nickname: '',
          tel: '',
          type: '',
          title: '',
          is_branch: 0,
          is_partner: '',
          state: '',
          status: '',
          address: '',
          head_img: '',
          city: null,
          picture: '',
          facilities: []
        },
        rules: {
          parent_id: [{
            required: true,
            message: '请选择上级结构',
            trigger: 'blur'
          }, ],
          title: [{
              required: true,
              message: '请输入机构名称',
              trigger: 'change'
            },

          ],
          type: [{
            required: true,
            message: '请至少选择一个类型',
            trigger: 'change'
          }, ],
          nickname: [{
            required: true,
            message: '请输入联系人',
            trigger: 'change'
          }, ],

          tel: [{
              required: true,
              message: '请输入手机号',
              trigger: 'change'
            },

            {
              pattern: /^1\d{10}$/,
              message: '手机号有误',
              trigger: 'change'
            },
          ],
          city: [{
            required: true,
            message: '请选择城市！',
            trigger: 'change'
          }, ],
          is_branch: [{
            required: true,
            message: '请选择服务网点！',
            trigger: 'change'
          }, ],
          is_partner: [{
            required: true,
            message: '请选择运营方式！',
            trigger: 'change'
          }, ],
          facilities: [{
            required: true,
            message: '请选择基础设施！',
            trigger: 'blur'
          }, ],
          head_img: [{
            required: true,
            message: '请上传封面图',
            trigger: 'change'
          }, ],
          picture: [{
            required: true,
            message: '请上传详情图',
            trigger: 'change'
          }],

          address: [{
            required: true,
            message: '请选择地址',
            trigger: 'blur'
          }, ],
        },
        typeOption: [{
            title: '总校',
            val: 1
          },
          {
            title: '分校',
            val: 2
          },
          {
            title: '报名点',
            val: 3
          },
          {
            title: '教练团队',
            val: 4
          },
        ],

        belong_typeOptions: [{
            label: '直营',
            value: 1,
          },
          {
            label: '加盟',
            value: 2,
          },
        ],
      }
    },
    components: {
      //基础dialog
      commonformdialog,
      //地图选择组件
      mapDialog,
      //上传图片组件
      uploader,
      Treeselect
    },
    props: {
      //是否显示弹窗
      isshowDialog: {
        type: Boolean,
        default: false,
        required: true,
      },
      //表单的名字
      dialogTitle: {
        type: String,
        default: '',
        required: true,
      },
      //是编辑还是新增
      formTypejg: {
        type: Number,
        default: 0
      },
      options: {
        type: Array,
        default: []
      }
    },
    methods: {
      normalizer(node) {
        return {
          id: node.id,
          label: node.title,
          children: node.children,
          isDisabled: node.option
        }
      },
      //删除图片
      head_imgdel() {
        this.xlcforms.head_img = ''
      },
      //上传图片成功
      head_imgok(imgUrl) {
        this.xlcforms.head_img = imgUrl
      },
      //删除图片
      picturedel() {
        this.xlcforms.picture = ''
      },
      //上传图片成功
      pictureok(imgUrl) {
        this.xlcforms.picture = imgUrl
      },
      closeDialog() {
        //重置表单 关闭弹窗
        this.$refs['xlcform'].resetFields()
        this.selectmapinfo = {}
        this.$emit('closedialog')
      },
      //选择地区触
      changeArea(val) {
        this.xlcforms.city = val[val.length - 1]
      },
      //确认提交表单
      async confirmbtn() {

        if (this.xlcforms.is_branch == 1) {
           if(this.xlcforms.parent_idTitle!=''){
             this.rules.parent_id=[]
           }
           this.$refs['xlcform'].validate(async (valid) => {

               if (!valid) return
               // TODO 提交表单
               let {
                 nickname,
                 tel,
                 type,
                 title,
                 is_branch,
                 is_partner,
                 state,
                 status,
                 address,
                 head_img,
                 city,
                 picture,
                 facilities,
                 parent_id,
                 lat,
                 lng
               } = this.xlcforms
               let params = {
                 nickname,
                 tel,
                 type,
                 title,
                 is_branch,
                 is_partner,
                 state,
                 status,
                 address,
                 head_img,
                 city,
                 picture,
                 parent_id,
                 lat,
                 lng,
                 facilities: facilities.join(','),

               }
               if (this.formTypejg == 0) {
                 let data = await schoolteamcreate(params)
                 if (data.code == '0000') {
                   this.$message({
                     type: 'success',
                     message: '新增成功!'
                   });
                   //清空数据
                   this.$refs['xlcform'].resetFields()
                   this.$emit('confirm')
                 }
               } else {

                 this.$parent.goschoolteamupdate()
               }

             })
        } else {
          let arr = ['type', 'nickname', 'tel', 'city', 'is_branch', 'is_partner']
          if(!this.xlcforms.parent_idTitle){
            arr=['parent_id', 'title', 'type', 'nickname', 'tel', 'city', 'is_branch', 'is_partner']
          }
          let num = 0
   
          this.$refs['xlcform'].validateField(arr, (
            error) => {
            if (error) {
              return false;
            } else {
              num++
            }
          })
          if (num == arr.length) {
            let {
              nickname,
              tel,
              type,
              title,
              is_branch,
              is_partner,
              state,
              status,
              address,
              head_img,
              city,
              picture,
              facilities,
              lat,
              lng,
              parent_id
            } = this.xlcforms
            let params = {
              nickname,
              tel,
              type,
              title,
              is_branch,
              is_partner,
              state,
              status,
              address,
              head_img,
              city,
              picture,
              lat,
              lng,
              parent_id,
              facilities: facilities.join(','),

            }
            if (this.formTypejg == 0) {
              let data = await schoolteamcreate(params)
              if (data.code == '0000') {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                });
                //清空数据
                this.$refs['xlcform'].resetFields()
                this.$emit('confirm')
              }
            } else {
              this.$parent.goschoolteamupdate()
            }
          }
        }
      },
      //选择地图
      selectmap() {
        let mapObj = {}
        this.isshowmap = true
      },
      //关闭地图
      closemap() {
        this.isshowmap = false
      },
      //确定选择地图
      affirmMap(params) {
        console.log('params', params)
        this.selectmapinfo = params
        this.xlcforms.address = params.address
        this.xlcforms.lat = params.lat
        this.xlcforms.lng = params.lng
        this.isshowmap = false

      },
      changeparent_id(val, i) {
        console.log(val)
        this.typeOption.forEach(item => {
          if (item.val > val.type.value) {
            item.disabled = false
          } else {
            item.disabled = true
          }
        })
      }
    },
    mounted() {
      //基础设施选项
      this.facilitiesOption = getSessionStorage('Options')[20]
      this.treeOptions = getSessionStorage('Optionsall').team
      this.teamRelation = getSessionStorage('userinfo').teamRelation
      this.teamType = getSessionStorage('userinfo').teamType
      this.typeOption.forEach(item => {
        if (item.val > this.teamType) {
          item.disabled = false
        } else {
          item.disabled = true
        }
      })
      this.$bus.on('editFrom', async (val) => {
        let params = val;
        this.selectmapinfo = val.selectmapinfo
        this.xlcforms = params.form
           console.log(this.xlcforms)
      })
    },
    watch: {

      'xlcforms.type': function(val) {
        if (val == 4) {
          this.xlcforms.is_branch = 0
        }
        if (val == 2) {
          this.rules.title = [{
              required: true,
              message: '请输入机构名称',
              trigger: 'change'
            },
            {
              pattern: /分校$/,
              message: '必须以“分校”结尾',
              trigger: 'blur'
            }
          ]
        } else if (val == 3) {
          this.rules.title = [{
              required: true,
              message: '请输入机构名称',
              trigger: 'change'
            },
            {
              pattern: /报名点$/,
              message: '必须以“报名点”结尾',
              trigger: 'blur'
            }
          ]
        } else if (val == 4) {
          this.rules.title = [{
              required: true,
              message: '请输入机构名称',
              trigger: 'change'
            },
            {
              pattern: /团队$/,
              message: '必须以“团队”结尾',
              trigger: 'blur'
            }
          ]
        }

      },
    },
    destroyed() {
      this.$refs['xlcform'].resetFields()
    },


  }
</script>

<style scoped lang='scss'>
  .formtips {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
    margin-left: 100px;

  }
</style>
